<template>
  <div class="face">
    <!-- 搜索框 -->
    <div class="searchContainer">
      <div class="searchTxtb">
        <!-- 输入框 -->
        <input
          type="text"
          v-model="inputValue"
          placeholder="请输入球员英文名称"
          @keyup.enter="searchRun"
          ref="myInput"
        />
        <loading v-if="isLoading" />
        <!-- 搜索按钮 -->
        <div class="button">
          <div @click="searchRun" class="searchRun">
            <div class="buttonMask"></div>
            <img class="faceSearch" src="@/assets/icon/faceSearch.png" />
            <img
              class="faceSearch-hover"
              style="display: none"
              src="@/assets/icon/faceSearch-hover.png"
            />
          </div>
        </div>
      </div>
    </div>
    <!-- 分页栏 -->
    <div class="pageController">
      <el-pagination
        v-model:current-page="pageNum"
        layout="prev, pager, next"
        @current-change="handleCurrentChange"
        :total="totalCount"
        v-show="!searchResultShow"
      />
      <div class="searchResultController" v-show="searchResultShow">
        <div>搜索结果如下</div>
        <div class="searchResultQuit" @click="pageRenew">退出</div>
      </div>
    </div>
    <!-- 主页面 -->
    <div class="mainContainer">
      <div
        class="picContainer"
        v-for="(pic, index) in picList"
        :key="index"
        @click="confirm(pic)"
        :style="{
          flex:
            picLength - index < picLength % 5 ||
            picLength - index === picLength % 5
              ? 0.5
              : 0.2,
        }"
      >
        <div class="faceCount">{{ pic.faceCount }}</div>
        <img ref="image" :src="pic.imagePath" @load="picLoadedHandler(pic)" />
        <div
          class="introduction"
          :style="{ backgroundColor: pic.bgColor, color: pic.fontColor }"
        >
          {{ pic.name }}
        </div>
        <div
          class="detail"
          :style="{
            background: 'linear-gradient(to top, ' + pic.detailBgColor + ')',
            color: pic.fontColor,
          }"
        >
          <div class="detailTitle">{{ pic.name }}</div>
          <div
            class="detailContent"
            v-for="(detail, index1) in pic.detail"
            :key="index1"
          >
            <div :style="{ backgroundColor: pic.fontColor }"></div>
            <span>{{ detail.key }}</span
            >: <span>{{ detail.value }}</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
/*eslint-disable*/
import { getCurrentInstance, onMounted } from "vue";
import { ElMessage } from "element-plus";
import pubsub from "pubsub-js";
import { useStore } from "vuex";

import mainApi from "@/api/mainApi";
import imgApi from "@/api/imgApi";

export default {
  name: "球员面补总起",
  props: {
    propsData: {
      type: Object,
      default: "",
    },
  },
  data() {
    return {
      picList: [],
      picLength: 15,
      inputValue: "",
      pageNum: 1,
      totalCount: 0,
      searchResultShow: false,
    };
  },
  setup() {
    const { proxy } = getCurrentInstance();
    const store = useStore();

    // 待传输的mod
    let modName, modPath;

    // 面补文件夹数组
    let faceFolderList = [];

    onMounted(() => {
      // 读取数据
      readData(proxy.propsData.propName);
      // 路由信息存储至vuex
      uploadVuex();
    });

    // 读取文件仓库路径
    function readData() {
      // 读取文件仓库中的文件
      mainApi.readJson(ElMessage, (data) => {
        // 遍历文件路径
        // traverseDirectory(window.myApi.path.join(data.fileHouse, "/face"));
        initPaginate(window.myApi.path.join(data.fileHouse, "/face"));
      });
    }

    // 分页初始化
    function initPaginate(folderPath) {
      let fs = window.myApi.fs;

      if (!fs.existsSync(folderPath)) {
        console.log("文件夹不存在:", folderPath);
        return;
      }

      let files;
      try {
        // 读取文件夹内容
        files = fs.readdirSync(folderPath);
      } catch (error) {}

      // 读取面补集mod数量
      let promises = files.map((file) => {
        return modPaginate(folderPath, file);
      });

      Promise.all(promises).then((res) => {
        faceFolderList = res;
        // 所有异步操作完成后执行排序
        faceFolderList.sort((a, b) => b.faceCount - a.faceCount);
        // 总页数计算
        proxy.totalCount = (Math.floor(res.length / 15) + 1) * 10;
        // 读取第一页
        pageRenew();
      });
    }

    // mod分页初始化
    async function modPaginate(folderPath, file) {
      let fs = window.myApi.fs;
      let path = window.myApi.path;
      return new Promise((resolve) => {
        // 面补集下属面补个数
        let faceCount = fs.readdirSync(path.join(folderPath, file)).length;
        // mod名称
        let name = removeChinese(
          fs.readdirSync(path.join(folderPath, file))[0].split(" ")[1]
        );

        // 载入内容
        resolve({
          folderPath: path.join(folderPath, file),
          faceCount,
          name,
        });
      });
    }

    // mod信息读取与填入
    async function modInfoReadAndInput(folderPath) {
      let fs = window.myApi.fs;
      let path = window.myApi.path;

      return new Promise((resolve) => {
        // 面补集下属面补个数
        let faceCount = fs.readdirSync(folderPath).length;
        // 读取第一个面补的文件夹名称
        let faceSet = fs.readdirSync(folderPath)[0];
        // 第一个面补的路径
        // console.log(folderPath, file, faceSet);
        let faceSetFolderPath = path.join(folderPath, faceSet);
        // 第一个面补的预览图
        let fullPath = path.join(faceSetFolderPath, "preview");
        // 图片路径
        fullPath = path.join(fullPath, fs.readdirSync(fullPath)[0]);
        // mod名称
        let name = removeChinese(faceSet.split(" ")[1]);
        // 作者
        let author = faceSet.split(" ")[2];
        // 开启读条
        pubsub.publish("pageLoading", true);
        // console.log(file, file.split(" "));
        // mod类型
        let type = mainApi.TypeDistinction(fullPath);

        // console.log(fullPath);
        // 读取图片为base64
        fs.readFile(fullPath, { encoding: "base64" }, (err, imageData) => {
          if (err) {
            ElMessage({
              message: `[${file}]图片读取失败`,
              type: "error",
              duration: 10000,
            });
            throw err;
          }

          // 载入内容
          resolve({
            imagePath: `data:image/jpeg;base64,${imageData}`,
            bgColor: null,
            fontColor: null,
            detailBgColor: null,
            folderPath,
            name: name.split("面补")[0],
            faceCount,
            detail: [
              {
                key: "类型",
                value: type,
              },
              {
                key: "作者",
                value: author,
              },
            ],
          });
        });
      });
    }

    // 路由信息暂存至vuex
    function uploadVuex() {
      store.commit("writeRouteData", {
        // 目标组件
        moduleName: proxy.propsData.origin_nav,
        // 选中球队
        teamName: proxy.propsData.propName,
      });
    }

    // 选择球员
    function confirm(data) {
      modPath = data.folderPath;
      console.log(modPath);
      // 页面跳转至mod详细界面
      pubsub.publish("routerChange", {
        modPath,
        origin_nav: "face",
        startComponent: "face",
        targetComponent: "faceSet",
      });
    }

    // 球员查询执行
    async function searchRun() {
      let value = proxy.inputValue;
      // console.log(`查询：${value}`);
      // 关键字匹配
      let searchResult = [];
      faceFolderList.forEach((element) => {
        if (element.name.toLowerCase().indexOf(value.toLowerCase()) != -1)
          searchResult.push(element);
      });
      // 信息提示
      ElMessage({ message: `共读取${searchResult.length}条数据` });
      // 页面更新
      proxy.picLength = searchResult.length;
      proxy.picList = [];
      proxy.searchResultShow = true;
      for (let index = 0; index < searchResult.length; index++) {
        proxy.picList.push(
          await modInfoReadAndInput(searchResult[index].folderPath)
        );
      }
    }

    // 删除中文字符
    function removeChinese(str) {
      return str.replace(/[\u4e00-\u9fa5]+/g, "");
    }

    // 选页响应器
    function handleCurrentChange(newPage) {
      proxy.pageNum = newPage;
      pageRenew();
    }

    // 页面更新
    async function pageRenew() {
      // 搜索结果隐藏
      proxy.searchResultShow = false;
      // 读取总数计算
      proxy.picLength =
        faceFolderList.length - (proxy.pageNum - 1) * 15 > 15
          ? 15
          : faceFolderList.length - (proxy.pageNum - 1) * 15;
      // 列表置空
      proxy.picList = [];
      // 按15个分页
      for (let i = 0; i < faceFolderList.length; i++) {
        if (
          (i > (proxy.pageNum - 1) * 15 || i === (proxy.pageNum - 1) * 15) &&
          i < proxy.pageNum * 15
        ) {
          // 读取与填入
          proxy.picList.push(
            await modInfoReadAndInput(faceFolderList[i].folderPath)
          );
          // console.log(proxy.picList);
        }
      }
    }

    return {
      confirm,
      searchRun,
      handleCurrentChange,
      pageRenew,
    };
  },
  methods: {
    picLoadedHandler(pic) {
      const image = this.$refs.image[this.picList.indexOf(pic)];
      imgApi.extractbgColor(image, pic).then(() => {
        pubsub.publish("loadingDataRenew", {
          loadingCount: this.picList.indexOf(pic) + 1,
          loadingSum: this.picLength,
        });
        // 加载完成后关闭加载页面
        if (this.picList.indexOf(pic) + 1 === this.picLength) {
          pubsub.publish("pageLoading", false);
        }
      });
    },
  },
};
</script>

<style lang="less" scoped>
@import "../less/variables.less";
.face {
  height: 94%;
  width: 100%;
  position: relative;
  top: 3px;
  display: flex;
  align-items: center;
  flex-direction: column;

  > * {
    width: 100%;
    // border: @border;
  }
  > .searchContainer {
    flex: 0.05;
    display: flex;
    align-items: center;
  }
  > .pageController {
    margin: 0.5% 0;
    display: flex;
    > .searchResultController {
      display: flex;
      width: 100%;
      align-items: center;
      > .searchResultQuit {
        margin-left: 5px;
        color: white;
        font-weight: bold;
        background-color: @red;
        border-radius: 5px;
        padding: 3px 5px;
      }
      > .searchResultQuit:hover {
        cursor: pointer;
      }
    }
  }
  > .mainContainer {
    flex: 0.95;
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
  }
}

.searchTxtb {
  // box-shadow: 0px 0px 2px 2px rgba(0, 0, 0, 0.1);
  border: @border;
  // background-color: white;
  height: 35px;
  width: 400px;
  border-radius: 5px;
  overflow: hidden;
  transition: width 0.5s ease;
  display: flex;
  align-items: center;
  position: relative;
  > input {
    flex: 0.85;
    height: 75%;
    padding-left: 5px;
    border-radius: 5px;
    margin-left: 1%;
    border: transparent 1px solid;
    background-color: transparent;
    // border: @border;
  }

  > input:focus,
  input:hover {
    // border: @red 1px solid;
    outline: none;
  }

  > .button {
    // width: 9%;
    height: 80%;
    display: flex;
    flex-direction: row;
    justify-content: center;
    align-items: center;
    position: absolute;
    right: 1%;
    > div {
      width: 100%;
      height: 100%;
      min-width: 50px;
      border-radius: 5px;
      font-family: "黑体";
      font-size: 90%;
      color: @red;
      transition: color 0.3s ease;
      display: flex;
      justify-content: center;
      align-items: center;
      > .buttonMask {
        position: absolute;
        z-index: 0;
        background-color: @red;
        top: 0%;
        left: 0%;
        width: 0%;
        height: 100%;
        transition: width 0.3s ease;
        border-radius: 5px;
      }
      > img {
        position: absolute;
        width: 20px;
      }
    }
    > div:hover {
      color: white;
      cursor: pointer;
    }
  }
}

.searchRun:hover > .buttonMask {
  width: 100% !important;
}

.searchRun:hover > .faceSearch {
  display: none;
}

.searchRun:hover > .faceSearch-hover {
  display: block !important;
}

/* 鼠标悬停时的滑块样式 */
.face::-webkit-scrollbar-thumb:hover {
  background-color: #555;
}

.picContainer {
  // flex: 0.2;
  box-shadow: 2px 2px 7px rgba(0, 0, 0, 0.7);
  border-radius: 10px;
  width: @jerseyWidth;
  height: @jerseyHeight;
  min-width: @jerseyWidth;
  overflow: hidden;
  margin: 2%;
  margin-top: 0%;
  position: relative;
  > .faceCount {
    position: absolute;
    top: -1%;
    right: -1%;
    width: 30px;
    height: 30px;
    border-bottom-left-radius: 10px;
    background-color: @red;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: bold;
    color: white;
  }
  > img {
    width: 100%;
    height: 100%;
    object-fit: cover;
    display: block;
  }
  > .introduction {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0% 1%;
    // font-size: @font4;
    font-size: 120%;
    font-weight: bold;
    position: absolute;
    top: @modNameTop;
    height: @modNameHeight;
    width: 100%;
    white-space: nowrap;
  }
  > .detail {
    position: absolute;
    bottom: 0;
    left: 0;
    width: 100%;
    height: 90%;
    padding: 5%;
    box-sizing: border-box;
    transform: translateY(100%);
    cursor: pointer;
    transition: transform 0.3s ease;
    > .detailTitle {
      font-weight: bold;
      font-size: 120%;
      margin-top: 75%;
    }
    > .detailContent {
      display: flex;
      align-items: center;
      margin: 4% 0%;
      font-size: 90%;
      > div {
        display: inline-block;
        width: 3px;
        height: 15px;
        border-radius: 15px;
        margin-right: 2%;
      }
    }
  }
}
.picContainer:hover .detail {
  transform: translateY(0);
  cursor: pointer;
}

.emptyPage {
  width: 40%;
  text-align: center;
  margin-left: 30%;
  margin-top: 5%;
  > img {
    width: 50%;
  }
}
</style>
  